import os
from time import sleep
import paho.mqtt.client as paho
import logging
import json
#引入线程
import threading


kt_list = [
    "党群活动室空调控制",
    "助理办公室空调控制",
    "财务室空调控制",
    "结算中心空调控制",
    "会议室空调控制（前区）",
    "中畅物流空调控制",
    "金融部空调控制",
    "党员活动室空调控制",
    "培训室空调控制",
    "会议室空调控制（后区）"
]

T_TOPIC = "zigbee2mqtt/空调设备/+/set"
OPEN = "DT4RPhG/AcoGvwF5Ar8BQAdAA0ALQAPgEwvAG8AHQC9AA0AP4BMDQCPgCwNAM0AXQAdAA0ALwAPAD8AHQBdAC8ADB8kUPhE+Eb8BQA/gAxtAC0ADwBfgCwvAG8AHQCNAA0AP4BMDQCPgCwNAM0AXQAdAA0ALwAPAD8AHQBdAC8ADB5PpPhE+Eb8BQA/gBxvgAw/AC0AHwAPAM8AP4A8HQCfgEwNAN0AfQAfgEwNAI+APA8GP4BM/4JgbAgK/AQ=="
CLOSE = "DT0RPRG/AcoGvwF4Ar8BQAdAA0ALQAPgEwvAG+ADB0ALwAPAP+ADD0ATwANAF+ADC0APQAPAE+APB0Aj4AgDBBQ9ET0RgBdANwDKIM9AA0ALQAPgEwvAG+ADB0ALwAPAP+ADD0ATwANAF+ADC0APQAPAE+APB0Aj4AQDAga/AQ=="
st = {

}


class MqttClient:
    def __init__(self, config: dict) -> None:
        global _log
        self._config = config
        self.ip = config["host"]
        self.port = config["port"]
        _log = logging.getLogger('mqtt')
        self._client = paho.Client(protocol=paho.MQTTv311)
        self._client.on_connect = lambda _, __, ____, rc: self.on_connect_cb(rc)
        self._client.on_message = self._on_message_cb
        self.kt_topic_list = []
        for kt in kt_list:
            self.kt_topic_list.append("zigbee2mqtt/空调设备/"+kt+"/set")
        self._topic = T_TOPIC
        with open(os.path.join(os.path.dirname(__file__),"ir_code_copy.json"), "r") as f:
            self.ir_code = json.load(f)

    def on_connect_cb(self, rc: int):
        print("conn okkkkk")
        _log.info("Connected mqtt broker %s with result: %d", self._config["host"], rc)

    def send_msg(self,  msg: dict, qos:int = 0,topic: str = T_TOPIC):
        payload = json.dumps(msg)
        print(f"mqtt发送数据topic:{topic},payload:{payload}")
        _log.debug("topic:",topic,"payload:",payload)
        self._client.publish(topic, payload, qos)

    def start(self):
        self._client.username_pw_set(username="juji1234", password="juji1234")
        self._client.connect(self._config["host"], self._config["port"], 60)
        self._client.loop_start()
        self._pro_sub_topic(self.kt_topic_list)
        while True:
            #轮询topic
            for k in self.kt_topic_list:
                tagm = {"t":1}
                self.send_msg(msg = tagm, topic=k.replace("/set",""))
                sleep(5)
            sleep(10)
            pass
    
    def stop(self):
        self._client.loop_stop()

    def _pro_sub_topic(self,topiclist:list):
        for topic in topiclist:
            self._client.subscribe(topic)
            print(topic)

    def _on_message_cb(self,client, userdata, msg):
        # print(msg.topic+" "+str(msg.payload))
        # print(msg.topic)
        # print(msg.payload)
        # print(msg.qos)
        # print(msg.retain)
        key = msg.payload.decode("utf-8")
        key = json.loads(key)
        newtopic = str(msg.topic.replace("/set",""))
        newpayload = {}
        print("newtopic",newtopic)
        print("payload:",key)
        
        if "ir_code_to_send" in key:
            if key["ir_code_to_send"] == OPEN:
                newpayload["state"] = "ON"
            elif key["ir_code_to_send"] == CLOSE:
                newpayload["state"] = "OFF"
            self.send_msg(msg = newpayload,topic=newtopic)
            sleep(0.1)
        if "SetAirVolume" in key:
            key["SetAirVolume"] = int(key["SetAirVolume"])
            self.send_msg(msg = key,topic=newtopic)
            if 0 < key["SetAirVolume"] <30:
                self.send_msg({"ir_code_to_send":self.ir_code["SetAirVolume"]["two"]},topic=msg.topic)
            elif 0 < key["SetAirVolume"]<70:
                self.send_msg({"ir_code_to_send":self.ir_code["SetAirVolume"]["four"]},topic=msg.topic)
            elif 0 < key["SetAirVolume"]<100:
                self.send_msg({"ir_code_to_send":self.ir_code["SetAirVolume"]["seven"]},topic=msg.topic)
        elif "SetTemperature" in key:
            key["SetTemperature"] = int(key["SetTemperature"])
            self.send_msg(msg = key,topic=newtopic)
            if key["SetTemperature"] == 17:
                self.send_msg({"ir_code_to_send":self.ir_code["SetTemperature"]["t17"]},topic=msg.topic)
            elif key["SetTemperature"] == 18:
                self.send_msg({"ir_code_to_send":self.ir_code["SetTemperature"]["t18"]},topic=msg.topic)
            elif key["SetTemperature"] == 19:
                self.send_msg({"ir_code_to_send":self.ir_code["SetTemperature"]["t19"]},topic=msg.topic)
            elif key["SetTemperature"] == 20:
                self.send_msg({"ir_code_to_send":self.ir_code["SetTemperature"]["t20"]},topic=msg.topic)
            elif key["SetTemperature"] == 21:
                self.send_msg({"ir_code_to_send":self.ir_code["SetTemperature"]["t21"]},topic=msg.topic)
            elif key["SetTemperature"] == 22:
                self.send_msg({"ir_code_to_send":self.ir_code["SetTemperature"]["t22"]},topic=msg.topic)
            elif key["SetTemperature"] == 23:
                self.send_msg({"ir_code_to_send":self.ir_code["SetTemperature"]["t23"]},topic=msg.topic)
            elif key["SetTemperature"] == 24:
                self.send_msg({"ir_code_to_send":self.ir_code["SetTemperature"]["t24"]},topic=msg.topic)
            elif key["SetTemperature"] == 25:
                self.send_msg({"ir_code_to_send":self.ir_code["SetTemperature"]["t25"]},topic=msg.topic)
            elif key["SetTemperature"] == 26:
                self.send_msg({"ir_code_to_send":self.ir_code["SetTemperature"]["t26"]},topic=msg.topic)
            elif key["SetTemperature"] == 27:
                self.send_msg({"ir_code_to_send":self.ir_code["SetTemperature"]["t27"]},topic=msg.topic)
            elif key["SetTemperature"] == 28:
                self.send_msg({"ir_code_to_send":self.ir_code["SetTemperature"]["t28"]},topic=msg.topic)
            elif key["SetTemperature"] == 29:
                self.send_msg({"ir_code_to_send":self.ir_code["SetTemperature"]["t29"]},topic=msg.topic)
            elif key["SetTemperature"] == 30:
                self.send_msg({"ir_code_to_send":self.ir_code["SetTemperature"]["t30"]},topic=msg.topic)
            else:
                self.send_msg({"ir_code_to_send":self.ir_code["SetTemperature"]["t17"]},topic=msg.topic)
        else:
            pass

if __name__ == "__main__":
    # 1. 创建一个mqtt客户端
    config = {}
    config["host"] = "192.168.1.100"
    config["port"] = 1883

    mqc = MqttClient(config)
    mqc.start()

